﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace UI.Share.Processing
{
    /// <summary>
    /// UploadifyUpload 的摘要说明
    /// </summary>
    public class UploadifyUpload : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string columnName=context.Request.QueryString["columnName"];
            // upload files
            HttpPostedFile fileData = context.Request.Files["Filedata"];
            if (fileData != null)
            {
                string result = null;

                try
                {
                    // 取上载文件后缀名
                    string extension = GetFileExt(fileData.FileName);
                    string upext = "txt,rar,zip,doc,docx,xls,xlsx,ppt,pptx,pdf,swf,jpg,jpeg,gif,png,bmp,wmv,avi,rm,mp4,wma,mp3,mid";
                    if (("," + upext + ",").IndexOf("," + extension + ",") < 0)
                    {
                        result = "不允许的文件类型";
                        context.Response.Write(result);
                        context.Response.End();
                        return;
                    };

                    string fileExt = Path.GetExtension(fileData.FileName);
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;

                    string RelativeDir = "/Upload/Uploadify/"+columnName+"/";

                    string dir = context.Server.MapPath(RelativeDir);

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    fileData.SaveAs(Path.Combine(dir, fileName));
                    result = RelativeDir + fileName;
                }
                catch
                {
                    result = null;
                }
                context.Response.Write(result);
                context.Response.End();
            }
            context.Response.End();
        }

        string GetFileExt(string FullPath)
        {
            if (FullPath != "") return FullPath.Substring(FullPath.LastIndexOf('.') + 1).ToLower();
            else return "";
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}